package com.cat.dataStructure03;

import javax.naming.CannotProceedException;
import java.util.*;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/grid-illumination/
 * @create 2025/11/3 09:44
 * @since JDK17
 */

public class Solution04 {
    static long N = ((int) 1e9);
    static int[][] dire = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    public int[] gridIllumination(int n, int[][] lamps, int[][] queries) {
        int m = queries.length, cnt = 0;
        int[] ans = new int[m];
        Map<Integer, Integer> r = new HashMap<>(), c = new HashMap<>(), d1 = new HashMap<>(), d2 = new HashMap<>();
        Set<Long> set = new HashSet<>();
        for (var p : lamps) {   // 收集所有开了的灯
            int x = p[0], y = p[1];
            r.merge(x, 1, Integer::sum);
            c.merge(y, 1, Integer::sum);
            d1.merge(x - y, 1, Integer::sum);
            d2.merge(x + y, 1, Integer::sum);
            set.add((long) x * N + y);
        }
        for (var q : queries) {
            int x = q[0], y = q[1];
            if (r.getOrDefault(x, 0) > 0 || c.getOrDefault(y, 0) > 0
                    || d1.getOrDefault(x - y, 0) > 0 || d2.getOrDefault(x + y, 0) > 0) {
                ans[cnt++] = 1;
            } else {
                ans[cnt++] = 0;
            }
            for (int i = Math.max(x - 1, 0); i <= Math.min(x + 1, N); i++) {
                for (int j = Math.max(y - 1, 0); j <= Math.min(y + 1, N); j++) {
                    long p = i * N + j;
                    if (set.contains(p)) {
                        set.remove(p);
                        r.merge(i, -1, Integer::sum);
                        c.merge(j, -1, Integer::sum);
                        d1.merge(i - j, -1, Integer::sum);
                        d2.merge(i + j, -1, Integer::sum);
                    }
                }
            }
        }

        return ans;
    }
}
